<template>
  <div class="goods-item" @click="goodsItemClick">
    <!-- TODO: 监听图片加载完成事件 -->
    <!-- 图片懒加载 -->
    <img v-lazy="getImg" alt="" @load="imageLoad" />
    <div class="goods-info">
      <p>{{ goodsItem.title }}</p>
      <span class="price">{{ goodsItem.price }}</span>
      <span class="collect">{{ goodsItem.cfav }}</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    goodsItem: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {}
  },
  computed: {
    getImg () {
      // 这里顺序还不能出错我曹了
      // return this.goodsItem.image || this.goodsItem.img || this.goodsItem.show.img
      return this.goodsItem.img
        ? this.goodsItem.img
        : this.goodsItem.image
          ? this.goodsItem.image
          : this.goodsItem.show.img
            ? this.goodsItem.show.img
            : this.throwErr()
    }
  },
  methods: {
    imageLoad () {
      // TODO: 使用事件总线监听图片加载完毕
      this.$bus.$emit('itemImgLoad')
    },
    // 点击商品跳转到详情页
    goodsItemClick () {
      let id = this.goodsItem.iid

      // 普通方式
      this.$router.push('/detail/' + id)

      // query方式
      // this.$router.push({ path: '/detail', query: { id } })
    },

    // 手动抛出错误
    throwErr () {
      throw new Error('未找到合适的图片属性')
    }
  },
  components: {}
}
</script>

<style lang="less" scoped>
.goods-item {
  padding-bottom: 40px;
  position: relative;
  width: 48%;
  font-size: 16px;

  img {
    width: 100%;
    border-radius: 5px;
  }

  .goods-info {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 5px;
    text-align: center;
    overflow: hidden;

    // 文字标题
    p {
      // 单行文字溢出显示省略号
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 3px;
    }

    // 价格
    .price {
      color: var(--color-high-text);
      margin-right: 20px;
    }
    // 收藏
    .collect {
      position: relative;

      // 伪元素图标
      &::before {
        content: "";
        position: absolute;
        left: -15px;
        top: 1px;
        width: 14px;
        height: 14px;
        background: url("~assets/images/common/collect.svg") no-repeat 0/14px,
          14px;
      }
    }
  }
}
</style>
